package cn.tude.egweibo4.controller;


import cn.tude.egweibo4.base.response.JsonResult;
import cn.tude.egweibo4.base.response.StatusCode;
import cn.tude.egweibo4.mapper.UserMapper;
import cn.tude.egweibo4.pojo.dto.UserLoginDTO;
import cn.tude.egweibo4.pojo.dto.UserRegDTO;
import cn.tude.egweibo4.pojo.entity.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;


import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("v1/users/")
@Api(tags = "01.用户模块")
public class UserController {
    @Autowired(required = false)
    private UserMapper userMapper;


    @PostMapping("reg")
    @ApiOperation(value = "注册")
    public JsonResult reg(@RequestBody UserRegDTO userRegDTO){
        String username=userRegDTO.getUsername();
        User user=userMapper.selectUserByUsername(username);
        if (user==null){
            int i = userMapper.insertUser(userRegDTO);
            if (i==1){
                return JsonResult.ok();
            }
            return JsonResult.notok();
        }
        return new JsonResult(StatusCode.USERNAME_EXIST);
    }


    @PostMapping("login")
    @ApiOperation(value="登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO,@ApiIgnore HttpSession session){
        String username=userLoginDTO.getUsername();
        User user=userMapper.selectUserByUsername(username);
        if (user==null){
            return new JsonResult(StatusCode.USERNAME_ERROR);
        }
        if (user.getPassword().equals(userLoginDTO.getPassword())){
            session.setAttribute("user",user);
            return JsonResult.ok();
        }
        return new JsonResult(StatusCode.PASSWORD_ERROR);
    }


    @GetMapping("currentUser")
    @ApiOperation(value = "获取当前用户")
    public JsonResult currentUser(@ApiIgnore HttpSession session){
        return JsonResult.ok(session.getAttribute("user"));
    }


    @GetMapping("logout")
    @ApiOperation(value = "退出登录")
    public JsonResult logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
        return JsonResult.ok();
    }


}
